package com.gzp.topic;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 主题的消费者
 * 
 * @author Administrator
 *
 */
public class TestTopicConsumer {

	private static final String brokerURL = "tcp://localhost:61616";
	private static final String topicName = "topic-hello";

	public static void main(String[] args) throws Exception {
		ConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);
		Connection connection = factory.createConnection();
		connection.start();
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Topic topin = session.createTopic(topicName);
		MessageConsumer messageConsumer = session.createConsumer(topin);
		System.out.println("3号消费者");
		messageConsumer.setMessageListener(new MessageListener() {

			@Override
			public void onMessage(Message message) {
				if (message instanceof TextMessage) {
					TextMessage textMessage = (TextMessage) message;
					try {
						System.out.println("接收到消息，消息内容为：" + textMessage.getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}

			}
		});
		System.in.read();
		messageConsumer.close();
		session.close();
		connection.close();
	}
}
